package com.xiaoju.manhattan.optimus.util;

import com.google.common.base.Stopwatch;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * HTTP 相关工具类
 * Created by lichengwen on 16/9/28.
 */
@Log4j2
public class HttpUtils
{
    
    public static String post(String url, Map<String, String> params, Charset charset, Map<String, String> headers)
    {
        log.info("request post:{} with params:{}", url, params);
        HttpPost post = new HttpPost(url);
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> e : headers.entrySet()) {
                post.addHeader(e.getKey(), e.getValue());
            }
        }
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> formParams = new ArrayList<>();
            for (Map.Entry<String, String> e : params.entrySet()) {
                formParams.add(new BasicNameValuePair(e.getKey(), e.getValue()));
            }
            post.setEntity(new UrlEncodedFormEntity(formParams, charset));
        }
        return sendRequest(post, charset);
    }
    
    private static String sendRequest(HttpUriRequest uriRequest, Charset charset)
    {
        try {
            CloseableHttpClient client;
            if ("https".equalsIgnoreCase(uriRequest.getURI().getScheme())) {
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
                {
                    //信任所有
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException
                    {
                        return true;
                    }
                }).build();
                sslContext.init(null, new TrustManager[] {TRUST_MANAGER}, null);
                //new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy());
                client = HttpClients.custom().setSSLSocketFactory(
                        new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build();
            } else {
                client = HttpClients.createMinimal();
            }
            
            
            Stopwatch sw = Stopwatch.createStarted();
            try (CloseableHttpResponse response = client.execute(uriRequest)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try {
                        String sResponse = EntityUtils.toString(entity, charset);
                        log.debug("response from {} => {}", uriRequest.getURI(), sResponse);
                        return sResponse;
                    } catch (IOException e) {
                        throw new RuntimeException("failed to read content from response.", e);
                    }
                } else {
                    return null;
                }
            } finally {
                log.info("time cost:" + sw.stop());
            }
        } catch (Exception e) {
            log.error("failed to execute http post.");
            throw new RuntimeException(e);
        }
    }
    
    public static String get(String url, Map<String, String> params, Charset charset, Map<String, String> headers)
    {
        log.info("Http get url: {}", url);
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null && !params.isEmpty()) {
                for (Map.Entry<String, String> e : params.entrySet()) {
                    uriBuilder.addParameter(e.getKey(), e.getValue());
                }
            }
            HttpGet get = new HttpGet(uriBuilder.build());
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, String> e : headers.entrySet()) {
                    get.addHeader(e.getKey(), e.getValue());
                }
            }
            return sendRequest(get, charset);
        } catch (Exception e) {
            throw new RuntimeException("failed to get:" + url, e);
        }
    }
    
    private static final X509TrustManager TRUST_MANAGER = new X509TrustManager()
    {
        public void checkClientTrusted(X509Certificate[] xcs, String string)
                throws CertificateException
        {
        }
        
        public void checkServerTrusted(X509Certificate[] xcs, String string)
                throws CertificateException
        {
        }
        
        public X509Certificate[] getAcceptedIssuers()
        {
            return null;
        }
    };
    
}
